import {useSearchParams} from "react-router-dom";
import {useRequest} from "ahooks";
import {LIST_PAGE_PARAM_KEY, LIST_PAGE_SIZE, LIST_PAGE_SIZE_PARAM_KEY, LIST_SEARCH_PARAMS_KEY} from "../constants";
import {getQuestionListService} from "../service/question";

type OptionType = {
    isDeleted: boolean,
    isStar: boolean,
    page: number,//第几页
    pageSize: number//每页多少条
}

function useLoadQuestionListData(opt: Partial<OptionType>) {
    const [searchParams] = useSearchParams()
    const {isDeleted = false, isStar = false} = opt
    const {loading, data, error, refresh} = useRequest(async () => {
        const keyword = searchParams.get(LIST_SEARCH_PARAMS_KEY) || ''
        const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '')
        const pageSize = parseInt(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY) || '') || LIST_PAGE_SIZE
        const data = await getQuestionListService({keyword, isDeleted, isStar, page, pageSize})
        return data
    }, {
        refreshDeps: [searchParams]
    })
    return {
        loading,
        data,
        error,
        refresh
    }
}

export default useLoadQuestionListData
